package com.xiaoming.e3mall.interceptor;

import com.xiaoming.e3mall.CartService;
import com.xiaoming.e3mall.common.utils.CookieUtils;
import com.xiaoming.e3mall.common.utils.E3Result;
import com.xiaoming.e3mall.common.utils.JsonUtils;
import com.xiaoming.e3mall.pojo.TbItem;
import com.xiaoming.e3mall.pojo.TbUser;
import com.xiaoming.e3mall.sso.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 订单业务:用户登录判断拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private CartService cartService;
    @Value("${SSO_URL}")
    private String SSO_URL;


    /**
     * 判断用户是否登录,如果登录就,将购物车列表展示
     * 没有登录就跳转到登录页面(并将当前请求的路径作为参数传递过来)
     * 登录之后直接返回拦截之前想要 请求的路径(这里就是订单web的首页)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断用户是否登录
        //从cookie中取tooken
        String token = CookieUtils.getCookieValue(request, "token", true);
        //如果浏览器中token存在说明登录了
        if (StringUtils.isNotBlank(token)) {
            //根据token从reids找查找用户信息(并更新redis中的生存时间)
            //这里我们直接焦勇tokenService
            E3Result e3Result = tokenService.getUserByToken(token);
            TbUser user = (TbUser) e3Result.getData();
            //如果模拟的session没有过期
            if (user != null) {
                //合并购物车(cartService)
                //判断cookie中是否有购物车数据,如果合并
                String cartList = CookieUtils.getCookieValue(request, "cart", true);
                if (StringUtils.isNotBlank(cartList))
                    cartService.mergeCart(user.getId(), JsonUtils.jsonToList(cartList, TbItem.class));

                //这个时候说明已经登录了我们应该要放行
                //这个时候我们需要把订单页面所需要的数据准备好
                request.setAttribute("user", user);
                //放行
                return true;
            } else {
                //如果用户登录过期了
                //跳转到登录页面,并把改request想要的请求的路径作为参数传过去,
                //这样登录之后就直接跳转到想要请求的路径(订单页面)在js中实现
                response.sendRedirect(SSO_URL + request.getRequestURL());
                return false;
            }
        }

        response.sendRedirect(SSO_URL + request.getRequestURL());
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
